﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.IO;
using EmoneyWeiXinCommon;
using EmoneyWeiXinEntity;
using EmoneyWeiXinBLL;

namespace EmoneyWeiXin.Controllers
{
    public class MaterialManageController : Controller
    {
        //
        // GET: /Material/
        string urlls = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}";
        string urlyj = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}";
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult AddPage()
        {
            return View();
        }

        public ActionResult GetListByPage()
        {

            int pageSize = int.Parse(Request["size"]);
            int pageIndex = int.Parse(Request["index"]);
            string whereText = "";
            string orderby = "";
            int totalCount = 0;
            List<MaterialEntity> lst = MaterialBLL.GetListByPage(pageSize, pageIndex, whereText, orderby, out totalCount);
            var obj = new { totalCount = totalCount, dataList = lst };
            return Content(JsonTools.ToJson(obj));
        }

        public ActionResult DoAdd()
        {

            string scName = Request["txtTitle"];
            string mediaType = Request["mediaType"];
            string timeType = Request["TimeType"];
            string weixinId = Request["weixinId"];
            string uploadUrl = "";  //上载的路径
            HttpPostedFileBase fileBase;
            string staticUrl = "~/Upload";
            if (Request.Files.Count > 0)
            {
                fileBase = Request.Files[0];
                string fileName = Guid.NewGuid().ToString() + Path.GetExtension(fileBase.FileName);
                string saveFullUrl = Server.MapPath(staticUrl) + "/" + fileName;
                fileBase.SaveAs(saveFullUrl);
                using (WebClient client = new WebClient())
                {
                    if (timeType == "yongjiu")  //判断素材是永久的还是临时的。
                    {
                        uploadUrl = urlyj;
                    }
                    else
                    {
                        uploadUrl = urlls;
                    }
                    MemcachedTools1 mmtools = new MemcachedTools1();
                    string keys = StringTools.ChangeRealKey("weixinUser", weixinId.ToString());
                    object objkyes = mmtools.Get(keys);
                    if (objkyes != null)
                    {
                        weixinUserEntity weixinUser = JsonTools.ToObject<weixinUserEntity>(objkyes.ToString());
                        uploadUrl = string.Format(uploadUrl, TokenHelper.GetToken(weixinUser.AppId, weixinUser.AppSecret), mediaType);
                        byte[] bsResult = client.UploadFile(uploadUrl, saveFullUrl);
                        string returnData = Encoding.Default.GetString(bsResult);
                        if (returnData.Contains("40001"))
                        {
                            TokenHelper.ClearToken(weixinUser.AppId); //刷新token
                            ViewBag.Result = "token失效，请刷新Token";
                        }
                        ReturnData2 rd2 = JsonTools.ToObject<ReturnData2>(returnData);
                        if (string.IsNullOrEmpty(rd2.errcode)) //正确的话，往数据库添加数据
                        {
                            MaterialEntity entity = new MaterialEntity();
                            entity.Ma_Type = mediaType;
                            entity.Ma_Type2 = timeType == "linshi" ? 0 : 1; ;
                            entity.ImgUrl = rd2.url == null ? "" : rd2.url;
                            entity.Ma_Name = scName;
                            entity.Media_id = rd2.media_id;
                            entity.weixinId = int.Parse(weixinId);
                            entity.RemaindTime = System.DateTime.Now.AddDays(3);
                            MaterialBLL.Insert(entity);
                            ViewBag.Result = "添加成功";
                        }
                        else
                        {
                            ViewBag.Result = "添加失败";
                        }
                    }
                    else
                    {
                        ViewBag.Result = "微信ID不存在";
                    }

                }
            }
            else
            {
                ViewBag.Result = "你没有选择文件";
            }
            return View();
        }


    }
    /// <summary>
    /// 素材上传返回实体
    /// </summary>
    class ReturnData2
    {
        public string media_id { get; set; }
        public string url { get; set; }
        public string errcode { get; set; }
        public string errmsg { get; set; }
    }
}
